package ils.domain.issue.model;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class ReserveRepositoryImpl implements ReserveRepository
{
    private static final String SELECT_RESERVE = "select reserve from Reserve as reserve where reserve.expiryDate > ? and reserve.status = 'N' order by reserveDate";
    private static final String SELECT_USER_BOOK = "select reserve from Reserve as reserve where reserve.userId = ? and reserve.bookId = ? and reserve.status = 'N'";
    private static final String SELECT_BOOK = "select reserve from Reserve as reserve where reserve.bookId = ? and reserve.status = 'N' order by reserve.reserveDate asc";
    private static final String RESERVE_USER = "select reserve from Reserve as reserve where reserve.userId = ? order by reserve.reserveDate asc";
    private SessionFactory sessionFactory;
    @Override
    public Reserve createReserve(Reserve reserve)
    {
        Session session = sessionFactory.getCurrentSession();
        session.save(reserve);
        return reserve;
    }
    public List<Reserve> getReservations(int firstResult, int maxResults){
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(SELECT_RESERVE);
        query.setDate(0, new Date());
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResults);
        return query.list();
    }
    @Override
    public Reserve getReserve(int userId, int bookId)
    {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(SELECT_USER_BOOK);
        query.setInteger(0, userId);
        query.setInteger(1, bookId);
        Iterator iterator = query.iterate();
        if(iterator.hasNext()) return (Reserve)iterator.next();
        else return null;
    }
    public void setSessionFactory(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }
    @Override
    public List<Reserve> getReservationsForBook(int bookId, int firstResult,
                                                int maxResults)
    {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(SELECT_BOOK);
        query.setInteger(0, bookId);
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResults);
        return query.list();
    }
    @Override
    public List<Reserve> getReservationsForUser(int userId)
    {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(RESERVE_USER);
        query.setInteger(0, userId);
        return query.list();
    }

    @Override
    public Reserve editReserve(Reserve reserve) {
        Session session = sessionFactory.getCurrentSession();
        session.update(reserve);
        return reserve;
    }
}
